﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Ext.Net;
using System.Xml;
using System.Xml.Xsl;

public partial class KMrpt5 : ExtBaseRpt
{
    MyDbHelper mydb = new MyDbHelper();
    string mid;
    protected void Page_Load(object sender, EventArgs e)
    {
        mid = Request.Params["mid"];
        if (!X.IsAjaxRequest)
        {
            //StoreColumns(mid);
            this.txtbdate.Text = DateTime.Now.ToString();
            this.txtedate.Text = DateTime.Now.ToString();
            BuildGridPanel2(mid, Session["UserID"].ToString());
            bindArea();
            this.txtseason.GetStore().DataSource = mydb.DM_GetDateSet("select distinct seasonname from v_mat");
            this.txtyear.GetStore().DataSource = mydb.DM_GetDateSet("select distinct yearno from v_mat order by yearno");
            this.txtmatkind.GetStore().DataSource = mydb.DM_GetDateSet("select distinct kindname from v_mat");
            this.txtstock.GetStore().DataSource = db.DM_GetDateSet("select stockid,stockname from bas_stock where stockname not like '%物资仓'");
            //binStock();
            //this.BuildGridPanel(mid,Session["UserID"].ToString()).AddTo(this.Viewport1);
        }
    }

    [DirectMethod(Namespace = "CompanyX")]
    public void binStock(string area)
    {
        //ShowBox(area);
        //string[] str = area.Split(',');
        //string p ="";
        //foreach (string s in str)
        //{
        //    p += "'" + s + "',";
        //}
        //p = p.TrimEnd(',');
        string sql = "";
        if (area == "[]")
        {
            sql = "select stockid,stockname from bas_stock where stockname not like '%物资仓'";
        }
        else
        {
            area = area.Replace("[", "");
            area = area.Replace("]", "");
            area = area.Replace("\"", "'");

            sql = @"select stockid,stockname from bas_stock where operationareaid in (" + area + ") and stockname not like '%物资仓' order by stockname";
            //ShowBox(sql);
        }
        this.txtstock.GetStore().DataSource = db.DM_GetDateSet(sql);
        this.st_stock.DataBind();
    }
    public void ComChange(Object sender, EventArgs e)
    {
        ShowBox(txtarea.Value.ToString());   
    }
    private void bindArea()
    {
        this.txtarea.GetStore().DataSource = db.DM_GetDateSet("select OperationAreaID,OperationAreaName from Bas_OperationArea");
    }
    //创建store的数据字段
    private void AddField(ModelField field)
    {
        if (X.IsAjaxRequest)
        {
            this.Store1.AddField(field);
        }
        else
        {
            this.Store1.Model[0].Fields.Add(field);
        }
    }
    private void StoreColumns(string mid)
    {
        if (X.IsAjaxRequest)
        {
            this.Store1.RemoveFields();
        }

        //Model m = new Model();
        string sql = @"select mu_id,lindx,fieldname,fielddisplay,mu_visible,fieldwidth from sys_moduleslayout a 
                    inner join sys_modulesuserlayout b on b.fid =lid 
                    inner join sys_modules m on m.mid = a.mid 
                    where m.parentid = " + mid + " and m.modulecode='GridView1'"
          + " and userid=" + Session["UserID"];
        DataSet ds = mydb.DM_GetDateSet(sql);
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            if (dr["mu_visible"].ToString().ToLower() == "true")
            {
                if (dr["fielddisplay"].ToString() != "")
                {
                    ModelField field = new ModelField();
                    field.Name = dr["fielddisplay"].ToString();
                    field.ServerMapping = dr["fieldname"].ToString();
                    field.Type = ModelFieldType.String;
                    this.AddField(field);
                    //this.AddField(new ModelField(dr["fieldname"].ToString().ToLower()));
                }
            }
        }
        this.Store1.PageSize = 50;
        this.Store1.RebuildMeta();
    }
    private GridPanel BuildGridPanel(string mid, string userid)
    {
        //动态创建用户网格
        return new GridPanel
        {
            Border = false,
            Title = mydb.DM_GetExecuteScalarObj("select modulename from sys_modules where mid=" + mid).ToString(),
            Store =  
            {
                this.Store1
            },
            SelectionModel = 
            { 
                new RowSelectionModel() { Mode = SelectionMode.Single }
            },
            ColumnModel =
            {
                Columns =
                { 
                    new RowNumbererColumn{
                        Width = 50
                    },
                    BuildColumns(mid,userid)
                }
            },
            View =
            {
               new Ext.Net.GridView()
               {
                    StripeRows = true,
                    TrackOver = true 
               }
            }
        };
    }
    private void BuildGridPanel2(string mid, string userid)
    {
        //动态创建用户网格
        this.GridPanel1.Title = mydb.DM_GetExecuteScalarObj("select modulename from sys_modules where mid=" + mid).ToString();
        this.GridPanel1.ColumnModel.Add(BuildColumns(mid,userid));
        this.GridPanel1.StoreID = "Store1";
        if (X.IsAjaxRequest)
        {
            this.GridPanel1.Reconfigure();
        }
    }

    private List<Column> BuildColumns(string mid,string userid)
    {
        List<Column> list = new List<Column>();

        string sql = @"select mu_id,lindx,fieldname,fielddisplay,mu_visible,fieldwidth,gridfoot from sys_moduleslayout a 
                    inner join sys_modulesuserlayout b on b.fid =lid 
                    inner join sys_modules m on m.mid = a.mid 
                    where m.parentid = " + mid + " and m.modulecode='GridView1'"
                 + " and userid=" + Session["UserID"]+" order by lindx";

        DataSet ds = mydb.DM_GetDateSet(sql);
        if (ds != null)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                if (dr["mu_visible"].ToString().ToLower() == "true")
                {
                    //合计
                    if (dr["gridfoot"].ToString() == "1")
                    {
                        SummaryColumn cl = new SummaryColumn();
                        cl.Text = dr["fielddisplay"].ToString();
                        cl.DataIndex = dr["fielddisplay"].ToString();
                        cl.Width = Convert.ToInt32(dr["fieldwidth"]);
                        cl.SummaryType = SummaryType.Sum;
                        list.Add(cl);
                    }
                    else
                    {
                        Column cl = new Column();
                        cl.Text = dr["fielddisplay"].ToString();
                        cl.DataIndex = dr["fielddisplay"].ToString();
                        cl.Width = Convert.ToInt32(dr["fieldwidth"]);
                        list.Add(cl);
                    }
                }
            }
        }
        return list;
    }

    private void QueryData()
    {
        //this.StoreColumns(mid);
        string area_str = StrSplitParam(this.txtarea);
        string stock_str = StrSplitParam(this.txtstock);
        string season = StrSplitParam(this.txtseason);
        string yearno = StrSplitParam(this.txtyear);
        string matkind = StrSplitParam(this.txtmatkind);
        DataSet ds = db.DM_GetDateSet(@"KM_SingProdSeleInvRpt '" + txtbdate.Text + "','" + txtedate.Text
           + "','" + area_str + "','" + stock_str + "','" + yearno + "','" + season + "','" + matkind + "','" + txtmatname.Text + "','" + txtmatcode.Text + "'");
        this.Store1.DataSource = ds;
        this.Store1.DataBind();
    }
    protected void BtnQureyUser(object sender, DirectEventArgs e)
    {
        //X.Msg.Alert("提示", "加载成功！").Show();
        QueryData();
    }
    protected void MyData_Refresh(object sender, StoreReadDataEventArgs e)
    {
        this.QueryData();
    }
    //导出EXCEL
    protected void Store1_Submit(object sender, StoreSubmitDataEventArgs e)
    {
        string format = this.FormatType.Value.ToString();

        XmlNode xml = e.Xml;

        this.Response.Clear();

        switch (format)
        {
            case "xml":
                string strXml = xml.OuterXml;
                this.Response.AddHeader("Content-Disposition", "attachment; filename=" + this.Title + ".xml");
                this.Response.AddHeader("Content-Length", strXml.Length.ToString());
                this.Response.ContentType = "application/xml";
                this.Response.Write(strXml);

                break;
            case "xls":
                this.Response.ContentType = "application/vnd.ms-excel";
                this.Response.AddHeader("Content-Disposition", "attachment; filename="+this.Title+".xls");
                XslCompiledTransform xtExcel = new XslCompiledTransform();
                xtExcel.Load(Server.MapPath("Excel.xsl"));
                xtExcel.Transform(xml, null, Response.OutputStream);

                break;
            case "csv":
                this.Response.ContentType = "application/octet-stream";
                this.Response.AddHeader("Content-Disposition", "attachment; filename=" + this.Title + ".csv");
                XslCompiledTransform xtCsv = new XslCompiledTransform();
                xtCsv.Load(Server.MapPath("Csv.xsl"));
                xtCsv.Transform(xml, null, Response.OutputStream);

                break;
        }

        this.Response.End();
    }
}